package com.example;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.util.Callback;
import javafx.scene.layout.HBox;
import java.io.IOException;
import java.util.List;
import java.util.Optional;

public class AdminCourseManagementController {
    @FXML private TableView<Course> courseTableView;
    @FXML private TableColumn<Course, Integer> idColumn;
    @FXML private TableColumn<Course, String> nameColumn;
    @FXML private TableColumn<Course, Double> creditsColumn;
    @FXML private TableColumn<Course, String> departmentColumn;
    @FXML private TableColumn<Course, String> courseTypeColumn;
    @FXML private TableColumn<Course, String> semesterColumn;
    @FXML private TableColumn<Course, String> descriptionColumn;
    @FXML private TableColumn<Course, Void> actionColumn;
    @FXML private TextField searchField;
    @FXML private ComboBox<Integer> pageSizeComboBox;

    private CourseDAO courseDAO;
    private ObservableList<Course> courseList;

    @FXML
    public void initialize() {
        courseDAO = new CourseDAO();
        courseList = FXCollections.observableArrayList();

        // 初始化表格列
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        creditsColumn.setCellValueFactory(new PropertyValueFactory<>("credits"));
        departmentColumn.setCellValueFactory(new PropertyValueFactory<>("department"));
        courseTypeColumn.setCellValueFactory(new PropertyValueFactory<>("courseType"));
        semesterColumn.setCellValueFactory(new PropertyValueFactory<>("semester"));
        descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description"));

        // 设置操作列
        actionColumn.setCellFactory(createActionButtonCellFactory());

        // 设置表格数据
        courseTableView.setItems(courseList);

        // 初始化分页大小选择框
        pageSizeComboBox.setItems(FXCollections.observableArrayList(10, 20, 50, 100));
        pageSizeComboBox.getSelectionModel().selectFirst();

        // 加载初始数据
        loadCourseData();
    }

    private void loadCourseData() {
        List<Course> courses = courseDAO.getAllCourses();
        courseList.setAll(courses);
    }

    @FXML
    private void handleAddCourse() {
        showCourseDialog(null);
    }

    @FXML
    private void handleSearch() {
        String keyword = searchField.getText().trim();
        if (!keyword.isEmpty()) {
            List<Course> searchResults = courseDAO.searchCourses(keyword);
            courseList.setAll(searchResults);
        } else {
            loadCourseData();
        }
    }

    private void showCourseDialog(Course course) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("CourseDialog.fxml"));
            Scene scene = new Scene(loader.load());

            CourseDialogController controller = loader.getController();
            controller.setCourse(course);

            Stage dialogStage = new Stage();
            dialogStage.setTitle(course == null ? "添加课程" : "编辑课程");
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            dialogStage.setScene(scene);

            controller.setDialogStage(dialogStage);

            dialogStage.showAndWait();

            if (controller.isConfirmed()) {
                loadCourseData();
            }
        } catch (IOException e) {
            e.printStackTrace();
            showAlert(Alert.AlertType.ERROR, "错误", "无法打开课程编辑对话框");
        }
    }

    private Callback<TableColumn<Course, Void>, TableCell<Course, Void>> createActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<Course, Void> call(TableColumn<Course, Void> param) {
                return new TableCell<>() {
                    private final Button editButton = new Button("编辑");
                    private final Button deleteButton = new Button("删除");
                    private final HBox buttons = new HBox(5, editButton, deleteButton);

                    {
                        editButton.setOnAction(event -> {
                            Course course = getTableView().getItems().get(getIndex());
                            showCourseDialog(course);
                        });

                        deleteButton.setOnAction(event -> {
                            Course course = getTableView().getItems().get(getIndex());
                            handleDeleteCourse(course);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        setGraphic(empty ? null : buttons);
                    }
                };
            }
        };
    }

    private void handleDeleteCourse(Course course) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认删除");
        alert.setHeaderText("删除课程");
        alert.setContentText("确定要删除课程 \"" + course.getName() + "\" 吗？");

        Optional<ButtonType> result = alert.showAndWait();
        if (result.isPresent() && result.get() == ButtonType.OK) {
            if (courseDAO.deleteCourse(course.getId())) {
                loadCourseData();
                showAlert(Alert.AlertType.INFORMATION, "成功", "课程已成功删除");
            } else {
                showAlert(Alert.AlertType.ERROR, "错误", "删除课程失败");
            }
        }
    }

    private void showAlert(Alert.AlertType type, String title, String content) {
        Alert alert = new Alert(type);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
} 